package com.backend.config;



import com.backend.interceptor.JwtTokenFilter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

/**
 * 作者:xuSen
 * 日期2025/7/20 10:51
 * Spring Security + JWT 配置
 */
@Configuration
public class SecurityConfig {
    @Autowired
    private JwtTokenFilter jwtTokenFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                // 配置请求授权规则
                .authorizeHttpRequests(conf -> conf
                        //允许所有人访问OPTIONS请求
                        .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                        // 允许所有人访问登录注册相关接口
                        .requestMatchers("/api/auth/**", "/error").permitAll()
                        // 允许所有人访问 Swagger UI 相关接口
                        .requestMatchers(
                                "/swagger-ui.html",
                                "/swagger-ui/**",
                                "/v3/api-docs/**",
                                "/swagger-resources/**",
                                "/webjars/**",
                                "/doc.html" // 如果使用自定义路径
                        ).permitAll()
                        //刷新令牌和退出需要认证
                                .requestMatchers("/api/auth/token/refresh", "/api/auth/logout").authenticated()
                        .requestMatchers("/webjars/**").permitAll()
            .requestMatchers("/api/**").hasAnyRole("0","1","2")
            .requestMatchers("/admin/**").hasAnyRole("0","1","2")
                )
                // 禁用 CSRF 保护
                .csrf(AbstractHttpConfigurer::disable)
                // 配置跨域支持
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                // 会话管理配置
                .sessionManagement(conf -> conf
                        // 无状态会话策略，通常用于 RESTful API
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 添加 JWT 认证过滤器
                .addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class)

        // 构建 SecurityFilterChain
                .build();
    }

    @Bean
    public UrlBasedCorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 允许所有源，生产环境应该限制具体域名
        configuration.addAllowedOriginPattern("*");
        // 允许所有HTTP方法
        configuration.addAllowedMethod("*");
        // 允许所有请求头
        configuration.addAllowedHeader("*");
        // 允许携带凭证
        configuration.setAllowCredentials(true);
        // 预检请求的有效期，单位秒
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}
